package SwingView.Message;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import JDBC.MessageActivities;
import JDBC.PeopleActivities;
import SwingController.CmsPresenter;
import SwingModel.CmsMessage;
import SwingModel.CmsLecture;
import SwingModel.CmsUser;
import SwingView.CmsContentPanelModel;
import SwingView.CmsMainView;
public class CmsCPMessage extends CmsContentPanelModel{

	private JLabel jlTitle;
	private JPanel jpContent;
	private NewMessagePanel newMsgPanel;
	String replyMessageContent;
	

	public CmsCPMessage(){
		
		//helper panel to center the title panel
		JPanel jp = new JPanel();
		jp.setPreferredSize(new Dimension(650,280));
		jp.setOpaque(false);
		jp.setBorder(BorderFactory.createEmptyBorder());
		GridBagLayout gbl_jp = new GridBagLayout();
		jp.setLayout(gbl_jp);
		
		jlTitle = new JLabel("Messages");
		jlTitle.setFont(jlTitle.getFont().deriveFont(20.0f).deriveFont(Font.BOLD));
		jlTitle.setBorder(BorderFactory.createEmptyBorder(0, 8, 10, 8));
		GridBagConstraints gbc_jlTitle = new GridBagConstraints();
		gbc_jlTitle.insets = new Insets(10, 0, 0, 5);
		gbc_jlTitle.gridx = 0;
		gbc_jlTitle.gridy = 0;
		jp.add(jlTitle, gbc_jlTitle);
		
		newMsgPanel = new NewMessagePanel();
		GridBagConstraints gbc_panel_1 = new GridBagConstraints();
		gbc_panel_1.insets = new Insets(0, 0, 15, 0);
		gbc_panel_1.gridx = 0;
		gbc_panel_1.gridy = 1;
		gbc_panel_1.weighty = 1.0;
		jp.add(newMsgPanel, gbc_panel_1);
		
		//content panel
		jpContent = new JPanel();
		jpContent.setLayout(new GridBagLayout());
		jpContent.setOpaque(false);
		
		//Set up the scroll bar
		JScrollPane scroll = new JScrollPane(jpContent);
		scroll.setBorder(BorderFactory.createEmptyBorder());
		scroll.setOpaque(true);
		scroll.setPreferredSize(new Dimension(650,450));
		scroll.setBackground(Color.WHITE);
		
		//set up student Message panel and add components
		setLayout(new BorderLayout());
		add(jp,BorderLayout.NORTH);//Add title People
		
		add(scroll,BorderLayout.WEST);//Add People List
	}
	
	public void displayListOfMessages(List<CmsMessage> listOfMessages){
		jpContent.removeAll();
		int i = 0;
		for(CmsMessage message : listOfMessages){
			GridBagConstraints c = new GridBagConstraints();
			c.gridy = i;
			c.insets = new Insets(0, 40, 8, 40);
			c.fill = GridBagConstraints.HORIZONTAL;
			jpContent.add(new MessageEntryRow(message),c);
			
			i++;
		}
		
		//empty space at bottom - used to fill the bottom of the page
		//when the list is too short
		JPanel p = new JPanel();
		p.setOpaque(false);
		p.setBackground(Color.WHITE);
		GridBagConstraints c_p = new GridBagConstraints();
		c_p.gridy = i;
		c_p.fill = GridBagConstraints.VERTICAL;
		c_p.weightx=1.0;
		c_p.weighty=1.0;
		jpContent.add(p,c_p);
		
		jpContent.revalidate();
		jpContent.repaint();
		
		newMsgPanel.clearAllInput();
		List<CmsUser> usersList = new ArrayList<CmsUser>();
		usersList = PeopleActivities.getListOfPeople(CmsPresenter.user.getSelectedCourse().getCourseID());
		newMsgPanel.updateListOfPeople(usersList);
		newMsgPanel.revalidate();
		newMsgPanel.repaint();
	}
	
	public CmsMessage getComposedMessage(){
		return newMsgPanel.getComposedMessage();
	}
	
	
	private class MessageEntryRow extends JPanel{
		final static private int ROW_WIDTH = 550;
		final static private int ROW_HEIGHT = 50;
		
		final static private int DATE_NAME_COLUMN_SIZE = 100;
		private JButton viewButton;
		private JButton replyButton;
		private JButton deleteButton;
		private JButton sendButton;
		private JPanel jpMsgContent;
		private JTextArea jtfReplyContent;
		
		private CmsMessage msg;
		private JPanel jpButtons;
		
		public MessageEntryRow(CmsMessage msg){

			JLabel jlTitle;
			JLabel sentDate; //avai date
			JLabel pdTitle;
			JLabel expDate; //exp date
			JLabel edTitle;
			
			SimpleDateFormat sdf;
			
			this.msg = msg;
			
			//Set up the panel
			if(msg.getIsRead()) setBackground(Color.WHITE);
			else setBackground(Color.LIGHT_GRAY);
			setBorder(BorderFactory.createLineBorder(new Color(170,170,170), 1));
			setOpaque(true);
			setLayout(new GridBagLayout());
			
			//add the Title
			//Set up file name label
			String msgTitle = msg.getMessageTitle();
			jlTitle = new JLabel(msgTitle);
			jlTitle.setFont(jlTitle.getFont().deriveFont(15.0f).deriveFont(Font.BOLD));
			GridBagConstraints cf = new GridBagConstraints();
			cf.fill = GridBagConstraints.HORIZONTAL;
			cf.anchor = GridBagConstraints.LINE_START;
			cf.gridwidth = 2;
			cf.weightx = 1.0;
			cf.insets = new Insets(10,10,0,10);
			add(jlTitle,cf);
			
			//add "From" title:
			JLabel jlFrom = new JLabel("From: ");
			jlFrom.setFont(jlFrom.getFont().deriveFont(10.0f).deriveFont(Font.BOLD));
			GridBagConstraints cp = new GridBagConstraints();
			cp.insets = new Insets(0,10,0,5);
			cp.gridx = 0;
			cp.gridy = 1;
			cp.fill = GridBagConstraints.HORIZONTAL;
			cp.anchor = GridBagConstraints.LINE_START;
			add(jlFrom,cp);
			
			//add the sender name
			JLabel jlSender = new JLabel(PeopleActivities.getFullName(msg.getSender()));
			jlSender.setFont(jlSender.getFont().deriveFont(10.0f));
			jlSender.setForeground(new Color(40,40,40));
			GridBagConstraints cd = new GridBagConstraints();
			cd.insets = new Insets(0,5,0,10);
			cd.gridx = 1;
			cd.gridy = 1;
			cd.weightx = 1.0;
			cd.fill = GridBagConstraints.HORIZONTAL;
			cd.anchor = GridBagConstraints.LINE_START;
			add(jlSender,cd);
			
			//add "Sent date" title:
			pdTitle = new JLabel("Received Date: ");
			pdTitle.setFont(pdTitle.getFont().deriveFont(10.0f).deriveFont(Font.BOLD));
			cp = new GridBagConstraints();
			cp.insets = new Insets(0,10,0,5);
			cp.gridx = 0;
			cp.gridy = 2;
			cp.anchor = GridBagConstraints.LINE_START;
			cp.fill = GridBagConstraints.HORIZONTAL;
			add(pdTitle,cp);
			
			//add the sent date
			sentDate = new JLabel(CmsPresenter.sdf.format(new Date(msg.getReceivedDTM().getTime())));
			sentDate.setFont(sentDate.getFont().deriveFont(10.0f));
			sentDate.setForeground(new Color(40,40,40));
			cd = new GridBagConstraints();
			cd.insets = new Insets(0,5,0,10);
			cd.gridx = 1;
			cd.gridy = 2;
			cd.weightx = 1.0;
			cd.fill = GridBagConstraints.HORIZONTAL;
			cd.anchor = GridBagConstraints.LINE_START;
			add(sentDate,cd);
			
			jpButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,0));
			jpButtons.setOpaque(false);
			GridBagConstraints csd = new GridBagConstraints();
			csd.gridx = 0;
			csd.gridy = 3;
			csd.fill = GridBagConstraints.HORIZONTAL;
			csd.gridwidth = 2;
			csd.insets = new Insets(0,10,0,10);
			add(jpButtons,csd);
			
			//set up send button
			sendButton = new JButton ("Send");
			sendButton.setFont(sendButton.getFont().deriveFont(12.0f));
			sendButton.setForeground(Color.BLUE);
			sendButton.setOpaque(false);
			sendButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 8, 8));
			sendButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
			sendButton.setVisible(false);
			jpButtons.add(sendButton);
			
			//add the reply button
			replyButton = new JButton ("Reply");
			replyButton.setFont(replyButton.getFont().deriveFont(12.0f));
			replyButton.setForeground(Color.BLUE);
			replyButton.setOpaque(false);
			replyButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 8, 8));
			replyButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
			jpButtons.add(replyButton);
			
			//add the view button
			//set up view button
			viewButton = new JButton ("View");
			viewButton.setFont(viewButton.getFont().deriveFont(12.0f));
			viewButton.setForeground(Color.BLUE);
			viewButton.setOpaque(false);
			viewButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 8, 8));
			viewButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
			jpButtons.add(viewButton);
			
			//add the delete button
			//set up delete button
			deleteButton = new JButton ("Delete");
			deleteButton.setFont(viewButton.getFont().deriveFont(12.0f));
			deleteButton.setForeground(Color.BLUE);
			deleteButton.setOpaque(false);
			deleteButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 8, 8));
			deleteButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
			jpButtons.add(deleteButton);
			
			jpMsgContent = new JPanel(new BorderLayout());
			jpMsgContent.setOpaque(false);
			jpMsgContent.setVisible(false);
			GridBagConstraints c = new GridBagConstraints();
			c.gridx = 0;
			c.gridy = 4;
			c.gridwidth = 2;
			c.weighty = 1.0;
			c.insets = new Insets(0,10,10,10);
			c.fill = GridBagConstraints.BOTH;
			c.anchor = GridBagConstraints.CENTER;
			add(jpMsgContent,c);
			
			//Add View AL:
			viewButton.addActionListener(new ViewActionListener());
			deleteButton.addActionListener(new ALMessageDelete(msg));
			replyButton.addActionListener(new ReplyActionListener());
			sendButton.addActionListener(new SendReplyListener()); // recipientsList not needed
		}
		
		public class ALMessageDelete implements ActionListener{

			private CmsMessage msg;
			
			public ALMessageDelete(CmsMessage msg){
				this.msg = msg;
			}
			
			@Override
			public void actionPerformed(ActionEvent e) {
				CmsUser user = CmsPresenter.user;
				CmsMainView mainView = CmsPresenter.mainView;
				
				MessageActivities.deleteMessage(user.getUsername(), msg.getConversationID());
				
				mainView.displayMessagePage(MessageActivities.getListOfMessage(user.getUsername(), 
															user.getSelectedCourse().getCourseID()));
			}

		}
		
		public class ViewActionListener implements ActionListener{

			@Override
			public void actionPerformed(ActionEvent e) {
				if(viewButton.getText().equals("View")){
					viewButton.setText("Close");
					sendButton.setVisible(false);
					
					//Add message content to view
					JTextArea jtfContent = new JTextArea(msg.getMessageContent());
					jtfContent.setEditable(false);
					JScrollPane scr = new JScrollPane(jtfContent);
					scr.setPreferredSize(new Dimension(500,200));
					jpMsgContent.removeAll();
					jpMsgContent.add(scr,BorderLayout.CENTER);
					jpMsgContent.setVisible(true);
					jpMsgContent.revalidate();
					jpMsgContent.repaint();
					revalidate();
					repaint();
					
					if(!msg.getIsRead()){ //if message is not read yet
						msg.setIsRead(true); //set read
						MessageActivities.setRead(CmsPresenter.user.getUsername(), msg.getMessageID());
					}
					
				} else if(viewButton.getText().equals("Close")){
					viewButton.setText("View");
					sendButton.setVisible(false);
					jpMsgContent.removeAll();
					jpMsgContent.setVisible(false);
					revalidate();
					repaint();
					setBackground(Color.WHITE);
					
				} else{ 
					//The View button says "Cancel" when we are replying to a message
					//Cancel the reply
					
					viewButton.setText("View");
					replyButton.setVisible(true);
					sendButton.setVisible(false);
					deleteButton.setVisible(true);
					jpMsgContent.removeAll();
					jpMsgContent.setVisible(false);
					jpMsgContent.revalidate();
					revalidate();
					repaint();
					setBackground(Color.WHITE);
				}
			}
		}
		
		public class ReplyActionListener implements ActionListener{

			@Override
			public void actionPerformed(ActionEvent e) {
				if(replyButton.getText().equals("Reply")){ // If statement not required
					jpMsgContent.removeAll();
					jpMsgContent.revalidate();
					
					replyButton.setVisible(false);
					sendButton.setVisible(true);
					viewButton.setText("Cancel");
					deleteButton.setVisible(false);
					
					jtfReplyContent = new JTextArea("\n\n-----------------------------"
							+ "-------------------\nReceived: " + CmsPresenter.sdf.format(msg.getReceivedDTM()) + "\nFrom: " + PeopleActivities.getFullName(msg.getSender()) + "\n" + msg.getMessageContent());
					
					jtfReplyContent.setEditable(true); //Set to true
					JScrollPane scr = new JScrollPane(jtfReplyContent);
					scr.setPreferredSize(new Dimension(500,200));
					jpMsgContent.add(scr,BorderLayout.CENTER);
					jpMsgContent.setVisible(true);
					jpMsgContent.revalidate();
					revalidate();
					repaint();
					
					if(!msg.getIsRead()){
						msg.setIsRead(true);
						MessageActivities.setRead(CmsPresenter.user.getUsername(), msg.getMessageID());
					}
				}
			}
		}
	
		public class SendReplyListener implements ActionListener{

			@Override
			public void actionPerformed(ActionEvent e) {
				int msgID = msg.getMessageID();
				int conID = msg.getConversationID();
				
				String msgTitle;
				if(msg.getMessageTitle().substring(0, 3).equals("RE:")) msgTitle = msg.getMessageTitle();
				else msgTitle = "RE: " + msg.getMessageTitle();
				
				String msgContent = jtfReplyContent.getText();
				Date receivedDate = new Date();
				
				CmsMessage replyMsg = new CmsMessage(msgID,conID,msgTitle,msgContent,receivedDate,false,false,false,null);
				
				String courseID = CmsPresenter.user.getSelectedCourse().getCourseID();
				
				MessageActivities.replyMessage(courseID, replyMsg, msg.getSender());
				
				CmsPresenter.mainView.displayMessagePage(MessageActivities.getListOfMessage(CmsPresenter.user.getUsername(), courseID));
			}
			
		}
	}
	
	public class NewMessagePanel extends JPanel{

		private static final int PANEL_WIDTH = 600;
		private static final int PANEL_HEIGHT = 250;
		
		public JTextArea jtfTitle;
		public JTextArea jtfContent;
		public JButton clearButton;
		public JButton sendButton;
		private List<CmsUser> origRecips;
		private List<CmsUser> avaiRecips;
		private List<CmsUser> selectedRecips;
		private JButton jbtAddRecipient;
		private JTextArea jtfRecipients;
		private JButton jbtRemoveRecipient;
		
		
		public NewMessagePanel(){
			selectedRecips = new ArrayList<CmsUser>();
			avaiRecips = new ArrayList<CmsUser>();
			origRecips = new ArrayList<CmsUser>();
			
			setPreferredSize(new Dimension(600, 250));
			setMinimumSize(new Dimension(PANEL_WIDTH,PANEL_HEIGHT));
			setMaximumSize(new Dimension(PANEL_WIDTH,PANEL_HEIGHT));
			setOpaque(false);
			setForeground(new Color(210,210,210));
			GridBagLayout gridBagLayout = new GridBagLayout();
			setLayout(gridBagLayout);
			
			
			JLabel jlbNewMessage = new JLabel("<HTML><U>New Message:<U><HTML>");
			jlbNewMessage.setFont(new Font("Lucida Grande", Font.BOLD, 17));
			GridBagConstraints gbc_jlbNewMessage = new GridBagConstraints();
			gbc_jlbNewMessage.anchor = GridBagConstraints.FIRST_LINE_START;
			gbc_jlbNewMessage.gridwidth = 2;
			gbc_jlbNewMessage.insets = new Insets(10, 10, 5, 0);
			gbc_jlbNewMessage.gridx = 0;
			gbc_jlbNewMessage.gridy = 0;
			add(jlbNewMessage, gbc_jlbNewMessage);
			
			JLabel lblRecipients = new JLabel("Recipients: ");
			lblRecipients.setFont(new Font("Lucida Grande", Font.BOLD, 13));
			GridBagConstraints gbc_lblRecipients = new GridBagConstraints();
			gbc_lblRecipients.insets = new Insets(0, 10, 5, 5);
			gbc_lblRecipients.anchor = GridBagConstraints.LINE_START;
			gbc_lblRecipients.gridx = 0;
			gbc_lblRecipients.gridy = 1;
			add(lblRecipients, gbc_lblRecipients);
			
			JPanel jpRecip = new JPanel(new FlowLayout(FlowLayout.LEFT,10,0));
			jpRecip.setOpaque(false);
			jpRecip.setBorder(new EmptyBorder(0, 0, 0, 0));
			
			
			jbtAddRecipient = new JButton("+ Add Recipient");
			jbtAddRecipient.setFont(jbtAddRecipient.getFont().deriveFont(12.0f));
			jbtAddRecipient.setForeground(Color.BLUE);
			jbtAddRecipient.setOpaque(false);
			jbtAddRecipient.setBorder(BorderFactory.createEmptyBorder(5, 5, 8, 8));
			jbtAddRecipient.setCursor(new Cursor(Cursor.HAND_CURSOR));
			jpRecip.add(jbtAddRecipient);
			
			jbtRemoveRecipient = new JButton("- Remove Recipient");
			jbtRemoveRecipient.setFont(jbtRemoveRecipient.getFont().deriveFont(12.0f));
			jbtRemoveRecipient.setForeground(Color.BLUE);
			jbtRemoveRecipient.setOpaque(false);
			jbtRemoveRecipient.setBorder(BorderFactory.createEmptyBorder(5, 5, 8, 8));
			jbtRemoveRecipient.setCursor(new Cursor(Cursor.HAND_CURSOR));
			jpRecip.add(jbtRemoveRecipient);
			
			GridBagConstraints gbc_jbtAddRecipient = new GridBagConstraints();
			gbc_jbtAddRecipient.fill = GridBagConstraints.HORIZONTAL;
			gbc_jbtAddRecipient.anchor = GridBagConstraints.LINE_START;
			gbc_jbtAddRecipient.insets = new Insets(0, 0, 5, 0);
			gbc_jbtAddRecipient.gridx = 1;
			gbc_jbtAddRecipient.gridy = 1;
			add(jpRecip, gbc_jbtAddRecipient);
			
			jtfRecipients = new JTextArea();
			jtfRecipients.setLineWrap(true);
			jtfRecipients.setWrapStyleWord(true);
			jtfRecipients.setOpaque(false);
			jtfRecipients.setVisible(false);
			jtfRecipients.setEditable(false);
			
			JLabel lblTo = new JLabel("To: ");
			lblTo.setFont(new Font("Lucida Grande", Font.BOLD, 13));
			GridBagConstraints gbc_lblTo = new GridBagConstraints();
			gbc_lblTo.anchor = GridBagConstraints.LINE_START;
			gbc_lblTo.insets = new Insets(0, 10, 5, 5);
			gbc_lblTo.gridx = 0;
			gbc_lblTo.gridy = 2;
			add(lblTo, gbc_lblTo);
			GridBagConstraints gbc_jtfRecipients = new GridBagConstraints();
			gbc_jtfRecipients.insets = new Insets(0, 0, 5, 10);
			gbc_jtfRecipients.fill = GridBagConstraints.BOTH;
			gbc_jtfRecipients.gridx = 1;
			gbc_jtfRecipients.gridy = 2;
			add(jtfRecipients, gbc_jtfRecipients);
			
			JLabel lblTitle = new JLabel("Title: ");
			lblTitle.setFont(new Font("Lucida Grande", Font.BOLD, 13));
			GridBagConstraints gbc_lblTitle = new GridBagConstraints();
			gbc_lblTitle.insets = new Insets(0, 10, 5, 5);
			gbc_lblTitle.anchor = GridBagConstraints.LINE_START;
			gbc_lblTitle.gridx = 0;
			gbc_lblTitle.gridy = 3;
			add(lblTitle, gbc_lblTitle);
			
			jtfTitle = new JTextArea();
			jtfTitle.setLineWrap(true);
			jtfTitle.setWrapStyleWord(true);
			
			JScrollPane spTitle = new JScrollPane(jtfTitle);
			spTitle.setPreferredSize(new Dimension(400,20));
			GridBagConstraints gbc_spTitle = new GridBagConstraints();
			gbc_spTitle.insets = new Insets(0, 0, 5, 10);
			gbc_spTitle.fill = GridBagConstraints.BOTH;
			gbc_spTitle.gridx = 1;
			gbc_spTitle.gridy = 3;
			add(spTitle, gbc_spTitle);
			
			JLabel lblContent = new JLabel("Content: ");
			lblContent.setFont(new Font("Lucida Grande", Font.BOLD, 13));
			GridBagConstraints gbc_lblContent = new GridBagConstraints();
			gbc_lblContent.weightx = 0.05;
			gbc_lblContent.anchor = GridBagConstraints.FIRST_LINE_START;
			gbc_lblContent.insets = new Insets(0, 10, 5, 5);
			gbc_lblContent.gridx = 0;
			gbc_lblContent.gridy = 4;
			add(lblContent, gbc_lblContent);
			
			jtfContent = new JTextArea();
			jtfContent.setWrapStyleWord(true);
			jtfContent.setLineWrap(true);
			
			JScrollPane spContent = new JScrollPane(jtfContent);
			GridBagConstraints gbc_spContent = new GridBagConstraints();
			gbc_spContent.weightx = 0.9;
			gbc_spContent.weighty = 1.0;
			gbc_spContent.insets = new Insets(0, 0, 5, 10);
			gbc_spContent.fill = GridBagConstraints.BOTH;
			gbc_spContent.gridx = 1;
			gbc_spContent.gridy = 4;
			add(spContent, gbc_spContent);
			
			JPanel panel = new JPanel();
			panel.setOpaque(false);
			GridBagConstraints gbc_panel = new GridBagConstraints();
			gbc_panel.gridwidth = 2;
			gbc_panel.fill = GridBagConstraints.BOTH;
			gbc_panel.gridx = 0;
			gbc_panel.gridy = 5;
			add(panel, gbc_panel);
			GridBagLayout gbl_panel = new GridBagLayout();
			gbl_panel.columnWidths = new int[]{186, 75, 75, 0};
			gbl_panel.rowHeights = new int[]{20, 0};
			gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
			gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
			panel.setLayout(gbl_panel);
			
			JButton clearButton = new JButton("Clear");
			GridBagConstraints gbc_clearButton = new GridBagConstraints();
			gbc_clearButton.anchor = GridBagConstraints.NORTHWEST;
			gbc_clearButton.insets = new Insets(0, 0, 10, 20);
			gbc_clearButton.gridx = 1;
			gbc_clearButton.gridy = 0;
			panel.add(clearButton, gbc_clearButton);
			clearButton.setFont(clearButton.getFont().deriveFont(Font.BOLD).deriveFont(13.0f));
			clearButton.setPreferredSize(new Dimension(75,20));
			clearButton.setMinimumSize(new Dimension(75,20));
			clearButton.setBackground(new Color(170,170,170));
			clearButton.setForeground(new Color(30,30,30));
			clearButton.setOpaque(true);
			clearButton.setBorder(BorderFactory.createLineBorder(new Color(30,30,30)));
			
			JButton sendButton = new JButton("Send");
			GridBagConstraints gbc_sendButton = new GridBagConstraints();
			gbc_sendButton.insets = new Insets(0, 20, 10, 0);
			gbc_sendButton.anchor = GridBagConstraints.NORTHWEST;
			gbc_sendButton.gridx = 2;
			gbc_sendButton.gridy = 0;
			panel.add(sendButton, gbc_sendButton);
			sendButton.setFont(sendButton.getFont().deriveFont(Font.BOLD).deriveFont(13.0f));
			sendButton.setPreferredSize(new Dimension(75,20));
			sendButton.setMinimumSize(new Dimension(75,20));
			sendButton.setBackground(new Color(170,170,170));
			sendButton.setForeground(new Color(30,30,30));
			sendButton.setOpaque(true);
			sendButton.setBorder(BorderFactory.createLineBorder(new Color(30,30,30)));
			
			//ACTION LISTENER
			//clear action listner
			clearButton.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					clearAllInput();
				}
				
			});
			
			boolean isNewMsg = true;
			
			List<CmsUser> listOfUserRecipients = getListOfRecipient();
			List<String> listOfRecipients = new ArrayList<String>();
			for(CmsUser userRecipient : listOfUserRecipients){
				listOfRecipients.add(userRecipient.getUsername());
			}
			
			sendButton.addActionListener(new SendMessageListener()); //The conversation ID is 0 for new messages
			//Later on when this new message is inserted into the Messages table, we set the conversation ID to equal the new message ID
			
			jbtAddRecipient.addActionListener(new AddRecipientListener());
			jbtRemoveRecipient.addActionListener(new RemoveRecipientListener());
			
			validate();
			repaint();
		}
		
		public void clearAllInput(){
			jtfTitle.setText("");
			jtfContent.setText("");
			this.avaiRecips = new ArrayList<CmsUser>(origRecips);
			this.selectedRecips = new ArrayList<CmsUser>();
			jbtRemoveRecipient.setEnabled(false);
			displayRecipients();
		}
		
		public String getTitle(){
			return jtfTitle.getText();
		}
		
		public String getContent(){
			if(jtfContent != null){
				return jtfContent.getText();
			} else{
				System.out.println("null jtfContent");
				return "null content";
			}
		}
		
		public CmsMessage getComposedMessage(){
			return new CmsMessage(0, 0, getTitle(), getContent(), new Date(),false, false, false, null); // IDs, date, IsRead, sender & recipients are ignored later on
		}
		
		public List<CmsUser> getListOfRecipient(){
			List<CmsUser> returnList = new ArrayList<CmsUser>(selectedRecips);
			System.out.println("----------------------------------------------\nSELECTED RECIPIENTS");
			for(CmsUser user : returnList){
				System.out.println(user.getFirstName());
			}
			System.out.println("----------------------------------------------\n");
			return new ArrayList<CmsUser>(selectedRecips);
		}
		
		public void updateListOfPeople(List<CmsUser> users){
			this.origRecips = users;
			this.avaiRecips = new ArrayList<CmsUser>(origRecips);
			this.selectedRecips = new ArrayList<CmsUser>();
			clearAllInput();
		}
		
		public boolean validateAllInputs(){
			if( selectedRecips.size() == 0){
				JOptionPane.showMessageDialog(CmsPresenter.mainView,
					    "No recipient was selected. Please select a recipient",
					    "ERROR!",
					    JOptionPane.ERROR_MESSAGE);
				return false;
			} else if(getTitle().equals("") && getContent().equals("")){
				JOptionPane.showMessageDialog(CmsPresenter.mainView,
					    "The message title and content fields are empty. Please enter a title and some content for your message",
					    "ERROR!",
					    JOptionPane.ERROR_MESSAGE);
				return false;
			} else if(getTitle().equals("")){
				JOptionPane.showMessageDialog(CmsPresenter.mainView,
					    "The message title field is empty. Please enter a title for your message",
					    "ERROR!",
					    JOptionPane.ERROR_MESSAGE);
				return false;
			} else if(getContent().equals("")){
				JOptionPane.showMessageDialog(CmsPresenter.mainView,
					    "The message content field is empty. Please enter some content for your message",
					    "ERROR!",
					    JOptionPane.ERROR_MESSAGE);
				return false;
			}
			else return true;
		}
		
		public void displayRecipients(){
			StringBuilder recip = new StringBuilder();
			for(CmsUser selectedRecip : selectedRecips){
				recip.append(selectedRecip.getFirstName() + " " + selectedRecip.getLastName() + "; ");
			}
			jtfRecipients.setText(recip.toString());
			jtfRecipients.setVisible(true);
		}
		
		class AddRecipientListener implements ActionListener{

			@Override
			public void actionPerformed(ActionEvent e) {
				Object[] recipList = new Object[avaiRecips.size() - 1];
				int i=0;
				int removeIndex=0;
				for(CmsUser user : avaiRecips){
					if(user.getUsername().equals(CmsPresenter.user.getUsername())){
						removeIndex = i;
						break;
					}
					i++;
				}
				avaiRecips.remove(removeIndex);
				
				i=0;
				for(CmsUser user : avaiRecips){
					recipList[i] = user.getFirstName() + " " + user.getLastName();
					i++;
				}
				
				
				String selectedRecip = (String) JOptionPane.showInputDialog(
	                    CmsPresenter.mainView,
	                    "Select an available recipient from the list below\n",
	                    "Select Recipient",
	                    JOptionPane.PLAIN_MESSAGE,
	                    null,
	                    recipList,
	                    null);
				
				removeIndex = 0;
				for(CmsUser user : avaiRecips){
					if(selectedRecip.equals(user.getFirstName() + " " + user.getLastName())){
						selectedRecips.add(avaiRecips.get(removeIndex));
						jbtRemoveRecipient.setEnabled(true);
						avaiRecips.remove(removeIndex);
						displayRecipients();
						break;
					}
					removeIndex++;
				}
			}
			
		}
		
		class RemoveRecipientListener implements ActionListener{

			@Override
			public void actionPerformed(ActionEvent e) {
				Object[] recipList = new Object[selectedRecips.size()];
				int i=0;
				for(CmsUser user : selectedRecips){
					recipList[i] = user.getFirstName() + " " + user.getLastName();
					i++;
				}
				
				String selectedRecip = (String) JOptionPane.showInputDialog(
	                    CmsPresenter.mainView,
	                    "Select an available recipient from the list below\n",
	                    "Select Recipient",
	                    JOptionPane.PLAIN_MESSAGE,
	                    null,
	                    recipList,
	                    null);
				
				int removeIndex = 0;
				for(CmsUser user : selectedRecips){
					if(selectedRecip.equals(user.getFirstName() + " " + user.getLastName())){
						avaiRecips.add(selectedRecips.get(removeIndex));
						selectedRecips.remove(removeIndex);
						if(selectedRecips.size() == 0) jbtRemoveRecipient.setEnabled(false);
						displayRecipients();
						break;
					}
					removeIndex++;
				}
				Collections.sort(avaiRecips,new UserComparator());
			}
			
		}
		
		public class UserComparator implements Comparator<CmsUser> {
		    @Override
		    public int compare(CmsUser o1, CmsUser o2) {
		        return o1.getUsername().compareTo(o2.getUsername());
		    }
		}
		
		class SendMessageListener implements ActionListener{

			@Override
			public void actionPerformed(ActionEvent e) {
				if(validateAllInputs()){
					CmsMessage newMsg = getComposedMessage();
					String courseID = CmsPresenter.user.getSelectedCourse().getCourseID();
					
					List<CmsUser> recipientsList = getListOfRecipient();
								
					MessageActivities.sendMessage(courseID, newMsg, recipientsList);
					
					clearAllInput();
					
					CmsPresenter.mainView.displayMessagePage(MessageActivities.getListOfMessage(CmsPresenter.user.getUsername(), courseID));
				}
			}
			
		}
		//Paint rounded rectangle on the back ground
		@Override
		protected void paintComponent(Graphics g){
			super.paintComponent(g);
			g.fillRoundRect(0, 0, this.getWidth(), this.getHeight(), 7, 7);
		}
	}
	
}
